package wisata.ina;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.R.string;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.AsyncPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.os.StrictMode;

import com.google.gson.Gson;
import com.google.gson.JsonParser;

public class PencarianActivity extends Activity implements OnItemSelectedListener{

	Boolean isInternetPresent = false;
	ConnectionDetector cd;
	AlertDialogManager alert = new AlertDialogManager();
	
	
	//String nama_Kota;
	String nama_Kota = "Kota Surabaya";
	//public static String nama_Kota = "Kota Surabaya";
	//String nama_Biaya;
	String nama_Biaya = "Murah";
	//String nama_Kategori;
	String nama_Kategori = "Kuliner";
	//String namaKota2;
	
	Spinner sKota;
	Spinner sBiaya;
	Spinner sKategori;
	
	EditText Judul;
	String[] biayaList;
	
	//private volatile JSONObject json;
	private final String URL_Kota ="http://ahmadsodik.phpnet.us/WebService/getKota.php";
	private final String URL_Kategori = "http://ahmadsodik.phpnet.us/WebService/getKategori.php";
	private final String URL_WisataByKota = "http://ahmadsodik.phpnet.us/WebService/WisataByKota.php";
	
	private ArrayList<Kota> KotaList = new ArrayList<Kota>();
	private ArrayList<Kategori> KategoriList = new ArrayList<Kategori>();
	
	//private Thread _thread;
	
	JSONParser jParser = new JSONParser();
	
    private static final String TAG_NAMEKOTA = "nama_kota";
    private static final String TAG_BIAYA = "nama_biaya";
    private static final String TAG_NAMEKATEGORI = "nama_kategori";
    private static final String TAG_SUCCESS = "success";
    
   // Intent i = new Intent(this, PencarianActivity.class);
    
    public void onClickNext1(){
		Intent intent = new Intent().setClass(this,HasilActivity .class);
		startActivity(intent);
	}
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pencarian);
		
		//Koneksi iternet
		cd = new ConnectionDetector(getApplicationContext());
		isInternetPresent = cd.isConnectingToInternet();
        if (!isInternetPresent) {
            // Internet Connection is not present
            alert.showAlertDialog(PencarianActivity.this, "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            return;
        }       
        
        
      //Spinner Kota
		sKota = (Spinner) findViewById(R.id.spinnerKota);
		new GetKota().execute();
		Log.e("aaaa", nama_Kota);
		sKota.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				nama_Kota = sKota.getSelectedItem().toString();
				Log.i(TAG_NAMEKOTA, nama_Kota);
				Toast.makeText(getApplicationContext(), nama_Kota+" selected", Toast.LENGTH_LONG).show();
				Log.e("gaplek", nama_Kota);
				//new GetKategori().execute();
				System.out.println(nama_Kota);
				setNamaKota(nama_Kota);
				//this.
				//new GetKategori.execute(nama_Kota);
				//super.Oncreate();

			}
			
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		Log.e("Namaaa KOtaaaaa", nama_Kota); //
		
		//Spinner Kategori
		sKategori = (Spinner) findViewById(R.id.spinnerKategori);
		new GetKategori().execute();
		sKategori.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				nama_Kategori = sKategori.getSelectedItem().toString();
				Log.i(TAG_NAMEKATEGORI, nama_Kategori);
				Toast.makeText(getApplicationContext(), nama_Kategori+" selected", Toast.LENGTH_LONG).show();
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		Log.e("Namaaa KOtaaaaa", nama_Kategori);
		
		//Spinner Biaya
		biayaList = getResources().getStringArray(R.array.spinner_biaya);
		sBiaya = (Spinner) findViewById(R.id.spinnerBiaya);
		ArrayAdapter<String> adapterBiaya = new ArrayAdapter<String>(PencarianActivity.this,
				android.R.layout.simple_spinner_dropdown_item, biayaList);		
		
		sBiaya.setAdapter(adapterBiaya);
		 
		sBiaya.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
	            @Override
	            public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
	            	nama_Biaya = sBiaya.getSelectedItem().toString();
					Log.i(TAG_BIAYA, nama_Biaya);
					Toast.makeText(getApplicationContext(), nama_Biaya+" selected", Toast.LENGTH_LONG).show();
				}
	 
	            @Override
	            public void onNothingSelected(AdapterView<?> arg0) {
	 
	            }
	     });
		//Log.e("Namaaa KOtaaaaaBiaaaaaya", nama_Biaya);
			
		//Aksion Button Cari
		Button button1 = (Button) findViewById(R.id.buttonCari);
		button1.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair(TAG_NAMEKOTA, nama_Kota));
            	
            	JSONObject jsonObjKategori = jParser.makeHttpRequest(URL_Kategori, "GET", params);	
				onClickNext1();
			}
		}); 
	}
	
	public void setNamaKota(String _kota) 
	{
		this.nama_Kota = _kota;
		//new GetKategori().execute();
	}

	/**
     * Adding spinner data
     * */
    private void populateSpinner() {
        List<String> lablesKota = new ArrayList<String>();
        List<String> lablesKategori = new ArrayList<String>();
        
        for (int i = 0; i < KotaList.size(); i++) {
            lablesKota.add(KotaList.get(i).getNama());
        }
        for (int i = 0; i < KategoriList.size(); i++) {
            lablesKategori.add(KategoriList.get(i).getNama());
        }
        
        // Creating adapter for spinner
        ArrayAdapter<String> spinnerAdapterKota = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lablesKota);
        // Drop down layout style - list view with radio button
        spinnerAdapterKota.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // attaching data adapter to spinner
        sKota.setAdapter(spinnerAdapterKota);
        
        // Creating adapter for spinner
        ArrayAdapter<String> spinnerAdapterKategori = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lablesKategori);
        // Drop down layout style - list view with radio button
        spinnerAdapterKategori.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // attaching data adapter to spinner
        sKategori.setAdapter(spinnerAdapterKategori);
    }
	
	private class GetKota extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ServiceHandler jsonParser = new ServiceHandler();
	        String jsonKota = jsonParser.makeServiceCall(URL_Kota, ServiceHandler.GET);
	 
	        Log.e("Response: ", "> " + jsonKota);
	 
	        if (jsonKota != null) {
	            try {
	                JSONObject jsonObjKota = new JSONObject(jsonKota);
	                if (jsonObjKota != null) {
	                	JSONArray kota = jsonObjKota.getJSONArray("kota");
	                    for (int i = 0; i < kota.length(); i++) {
	                        JSONObject catObj = (JSONObject) kota.get(i);
	                        Kota kot = new Kota(catObj.getString(TAG_NAMEKOTA));
	                        KotaList.add(kot);
	                        //Log.i(TAG_NAMEKOTA, kot.getNama());
	                    }
	                }
	 
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
	 
	        } else {
	            Log.e("JSON Data", "Didn't receive any data from server!");
	        }
	        return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			populateSpinner();
		}
		
	}	
	
	private class GetKategori extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
	            
	            	List<NameValuePair> params = new ArrayList<NameValuePair>();
	                params.add(new BasicNameValuePair(TAG_NAMEKOTA, nama_Kota));
	            	
	            	JSONObject jsonObjKategori = jParser.makeHttpRequest(URL_Kategori, "GET", params);
	            	
	                if (jsonObjKategori != null) {
	                	try {
	                	JSONArray kategori = jsonObjKategori.getJSONArray("kategori");
	                	Log.e("Response: ", "> " + kategori);
	                    for (int i = 0; i < kategori.length(); i++) {
	                        JSONObject catObj = (JSONObject) kategori.get(i);
	                        Kategori kat = new Kategori(catObj.getString(TAG_NAMEKATEGORI));
	                        KategoriList.add(kat);
	                        //Log.i(TAG_NAMEKATEGORI, kat.getNama());
	                    	}
	                	} catch (JSONException e) {
		                e.printStackTrace();
	                	}
	                	
	                }else {
	    	            Log.e("JSON Data", "Didn't receive any data from server!");
	    	        }
	                
	        return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			populateSpinner();
		}
		
	}
	
	private class Pencarian extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
	            
	            	List<NameValuePair> params = new ArrayList<NameValuePair>();
	                params.add(new BasicNameValuePair(TAG_NAMEKOTA, nama_Kota));
	                //params.add(new BasicNameValuePair(TAG_NAMEKATEGORI, nama_Kategori));
	                //params.add(new BasicNameValuePair(TAG_BIAYA, nama_Biaya));
	            	
	            	JSONObject jsonObjPencarian = jParser.makeHttpRequest(URL_WisataByKota, "GET", params);
	            	
	            	// check json success tag
	    			try {
	    				int success = jsonObjPencarian.getInt(TAG_SUCCESS);
	    				
	    				if (success == 1) {
	    					// successfully updated
	    					Intent i = getIntent();
	    					// send result code 100 to notify about product update
	    					setResult(100, i);
	    					finish();
	    					
	    					//Toast.makeText(InsertReport.this, "Simpan laporan berhasil", Toast.LENGTH_LONG).show();
	    				} else {
	    					// failed to update product
	    				}
	    			} catch (JSONException e) {
	    				e.printStackTrace();
	    			}

	    			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			populateSpinner();
		}
		
	}
	
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
}


